package com.woniuxy.microshoppingcartserver.controller;


import com.alibaba.fastjson.JSONObject;
import com.woniuxy.microshoppingcartserver.bean.CartItem;
import com.woniuxy.microshoppingcartserver.bean.ResponseMsg;
import com.woniuxy.microshoppingcartserver.service.CartService;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Resource
    private CartService cartServiceImpl;
    //从前端的local Storage中获得当前用户的id信息

    /**
     * 添加到购物车
     */

    @PostMapping(value = "/add/{goodsId}",produces = MediaType.APPLICATION_JSON_VALUE)
    public String addCart(@RequestParam("userId") String userId,@RequestParam("skuId") Integer skuId, @RequestParam("nums")Integer nums,@PathVariable("goodsId") Integer goodsId){
        //一个用户对应一个购物车，一个购物车对应多个商品
        cartServiceImpl.addToCart(skuId, nums,goodsId,userId);

        return JSONObject.toJSONString(ResponseMsg.builder().code(200).msg("成功添加购物车").build());
    }


    /**
     * 删除购物车
     */
    @DeleteMapping(value = "/{skuIds}",produces = MediaType.APPLICATION_JSON_VALUE)
    public String deleteCart(@PathVariable("skuIds") Integer[] skuIds,@RequestParam("userId") String userId){
        cartServiceImpl.deleteCart(skuIds,userId);
        return JSONObject.toJSONString(ResponseMsg.builder().code(200).msg("商品删除成功").build());
    }

    /**
     * 修改购物车商品数量
     */
    @PutMapping(value = "/nums/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    public String updateNumsCart(@PathVariable("id") Integer skuId,Integer nums,@RequestParam("userId") String userId){
        cartServiceImpl.updateNumsCart(skuId, nums,userId);
        return JSONObject.toJSONString(ResponseMsg.builder().code(200).msg("商品修改成功").build());
    }
    /**
     * 修改购物车商品型号
     */
    @PutMapping(value = "/{id1}/{id2}",produces = MediaType.APPLICATION_JSON_VALUE)
    public String updateTypeCart(@PathVariable("id1") Integer oldSkuId,@PathVariable("id2")Integer newSkuId,@RequestParam("userId") String userId){
        cartServiceImpl.updateTypeCart(oldSkuId, newSkuId,userId);
        return JSONObject.toJSONString(ResponseMsg.builder().code(200).msg("商品修改成功").build());
    }

    /**
     * 查看购物车
     */
    @GetMapping(value = "/look",produces = MediaType.APPLICATION_JSON_VALUE)
    public String lookCart(Integer start, Integer end,@RequestParam("userId") String userId){
        //刷新购物车zset 根据start和end获取购物车内容
        List<CartItem> items = cartServiceImpl.lookCart(start,end,userId);

        return JSONObject.toJSONString(ResponseMsg.builder().code(200).msg("").data(items).build());
    }


}
